<template>
  <el-dialog
    v-model="dialogVisible"
    :title="props.isModify ? '学生体测数据修改' : '学生体测数据录入'"
    width="700px"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>
    
    <div v-else-if="testItems.length === 0" class="empty-data">
      <el-empty description="没有需要测试的项目" />
    </div>
    
    <el-form v-else ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <div class="student-info">
        <div class="info-item">
          <span class="label">姓名：</span>
          <span class="value">{{ studentInfo.studentName }}</span>
        </div>
        <div class="info-item">
          <span class="label">学号：</span>
          <span class="value">{{ studentInfo.studentCode }}</span>
        </div>
        <div class="info-item">
          <span class="label">性别：</span>
          <span class="value">{{ studentInfo.gender === 1 ? '男' : '女' }}</span>
        </div>
        <div class="info-item">
          <span class="label">年级：</span>
          <span class="value">{{ getGradeText(studentInfo.gradeVal) }}</span>
        </div>
      </div>
      
      <el-divider>测试项目</el-divider>
      
      <el-form-item 
        v-for="item in testItems" 
        :key="item.id || item.itemId"
        :label="item.name"
        class="test-item-form-item"
      >
        <div class="score-input-container">
          <!-- 标题行 -->
          <div class="score-input-header">
            <div class="input-label">原始成绩</div>
            <div class="input-label">数值化得分</div>
          </div>
          
          <!-- 输入框行 -->
          <div class="score-input-row">
            <!-- 原始成绩输入 -->
            <el-form-item 
              :prop="`scoreInfo.${item.itemId || item.id}.grade`"
              class="nested-form-item"
            >
              <el-input-number 
                v-model="formData.scoreInfo[item.itemId || item.id].grade" 
                :min="item.minValue" 
                :max="item.maxValue"
                :step="0.01"
                :precision="2"
                controls-position="right"
                placeholder="原始成绩"
                @change="(val) => handleGradeChange(val, item)"
              />
              <span class="unit-text">{{ item.unit }}</span>
            </el-form-item>
            
            <!-- 数值化得分输入 -->
            <el-form-item 
              :prop="`scoreInfo.${item.itemId || item.id}.score`"
              class="nested-form-item"
            >
              <el-input-number 
                v-model="formData.scoreInfo[item.itemId || item.id].score" 
                :min="0" 
                :max="100"
                :step="0.1"
                :precision="1"
                controls-position="right"
                placeholder="数值化得分"
              />
              <span class="unit-text">分</span>
            </el-form-item>
          </div>
          
          <!-- 项目标签 -->
          <div class="tags-container">
            <el-tag 
              v-if="item.isBouns" 
              type="success" 
              effect="plain" 
              size="small" 
              class="item-tag"
            >
              加分项
            </el-tag>
            
            <el-tag 
              v-if="item.genderLimit !== 2" 
              type="info" 
              effect="plain" 
              size="small"
              class="item-tag"
            >
              {{ item.genderLimit === 0 ? '仅限男生' : '仅限女生' }}
            </el-tag>
          </div>
        </div>
        <div class="hint-text">
          有效原始成绩范围: {{ item.minValue }} - {{ item.maxValue }} {{ item.unit }}
        </div>
      </el-form-item>
      
      <el-form-item label="备注" prop="remark">
        <el-input 
          v-model="formData.remark" 
          type="textarea" 
          placeholder="请输入备注信息（选填）" 
          :rows="3"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ props.isModify ? '修改' : '提交' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getStudentTestItemListApi, submitStudentTestDataApi, getStudentTestDataApi, updateStudentTestDataApi } from '../api/modules/student';
import { calculateScore } from '../utils/scoreCalculator';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  studentInfo: {
    type: Object,
    default: () => ({})
  },
  isModify: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:visible', 'refresh']);

// 对话框可见性
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
});

// 表单引用
const formRef = ref(null);

// 加载状态
const loading = ref(false);
const submitting = ref(false);

// 测试项目列表
const testItems = ref([]);

// 表单数据
const formData = reactive({
  scoreInfo: {},
  remark: ''
});

// 表单验证规则
const rules = reactive({});

// 监听对话框可见性变化
watch(() => props.visible, (newVal) => {
  if (newVal && props.studentInfo.studentId) {
    // 重置表单
    resetForm();
    
    if (props.isModify) {
      // 获取学生体测数据
      fetchStudentTestData(props.studentInfo.studentId);
    } else {
      // 获取测试项目
      console.log('获取学生测试项目, studentId:', props.studentInfo.studentId);
      fetchTestItems(props.studentInfo.studentId);
    }
  }
});

// 获取测试项目
const fetchTestItems = async (studentId) => {
  loading.value = true;
  try {
    const res = await getStudentTestItemListApi(studentId);
    if (res && res.code === 1 && res.data) {
      testItems.value = res.data;
      
      // 初始化表单数据和验证规则
      initFormData();
    } else {
      testItems.value = [];
      ElMessage.warning('获取测试项目失败');
    }
  } catch (error) {
    console.error('获取测试项目失败', error);
    ElMessage.error('获取测试项目失败');
    testItems.value = [];
  } finally {
    loading.value = false;
  }
};

// 获取学生体测数据
const fetchStudentTestData = async (studentId) => {
  loading.value = true;
  try {
    const res = await getStudentTestDataApi(studentId);
    if (res && res.code === 1 && res.data) {
      // 初始化测试项目
      testItems.value = res.data;
      
      // 初始化表单数据
      initModifyFormData();
    } else {
      testItems.value = [];
      ElMessage.warning('获取体测数据失败');
    }
  } catch (error) {
    console.error('获取体测数据失败', error);
    ElMessage.error('获取体测数据失败');
    testItems.value = [];
  } finally {
    loading.value = false;
  }
};

// 处理原始成绩变化，自动计算数值化得分
const handleGradeChange = (val, item) => {
  if (val === null || val === undefined) return;
  
  // 使用项目名称计算得分
  const itemName = item.name;
  
  // 构造学生信息对象
  const studentInfo = {
    gender: props.studentInfo.gender,
    gradeVal: props.studentInfo.gradeVal
  };
  
  console.log('学生信息:', studentInfo);
  
  // 使用工具函数计算得分
  const score = calculateScore(itemName, val, studentInfo);
  
  // 如果得分有效，则更新数值化得分
  if (score > 0) {
    formData.scoreInfo[item.itemId || item.id].score = score;
  }
};

// 初始化表单数据和验证规则
const initFormData = () => {
  // 重置表单数据
  formData.scoreInfo = {};
  formData.remark = '';
  
  // 重置验证规则
  const newRules = {};
  
  // 为每个测试项创建表单项和验证规则
  testItems.value.forEach(item => {
    // 设置默认值
    formData.scoreInfo[item.itemId || item.id] = {
      grade: null, // 原始成绩
      score: null  // 数值化得分
    };
    
    // 设置验证规则 - 原始成绩
    newRules[`scoreInfo.${item.itemId || item.id}.grade`] = [
      { 
        required: true, 
        message: `请输入${item.name}的原始成绩`, 
        trigger: 'blur' 
      },
      { 
        type: 'number', 
        min: item.minValue, 
        max: item.maxValue, 
        message: `${item.name}的有效原始成绩范围为${item.minValue}-${item.maxValue}${item.unit}`, 
        trigger: 'blur' 
      }
    ];
    
    // 设置验证规则 - 数值化得分
    newRules[`scoreInfo.${item.itemId || item.id}.score`] = [
      { 
        required: true, 
        message: `请输入${item.name}的数值化得分`, 
        trigger: 'blur' 
      },
      { 
        type: 'number', 
        min: 0, 
        max: 100, 
        message: `${item.name}的有效数值化得分范围为0-100分`, 
        trigger: 'blur' 
      }
    ];
  });
  
  // 更新验证规则
  Object.assign(rules, newRules);
};

// 初始化修改表单数据
const initModifyFormData = () => {
  // 重置表单数据
  formData.scoreInfo = {};
  formData.remark = '';
  
  // 重置验证规则
  const newRules = {};
  
  // 为每个测试项创建表单项和验证规则
  testItems.value.forEach(item => {
    // 设置默认值
    formData.scoreInfo[item.itemId] = {
      grade: item.grade, // 原始成绩
      score: item.score  // 数值化得分
    };
    
    // 设置验证规则 - 原始成绩
    newRules[`scoreInfo.${item.itemId}.grade`] = [
      { 
        required: true, 
        message: `请输入${item.name}的原始成绩`, 
        trigger: 'blur' 
      },
      { 
        type: 'number', 
        min: item.minValue, 
        max: item.maxValue, 
        message: `${item.name}的有效原始成绩范围为${item.minValue}-${item.maxValue}${item.unit}`, 
        trigger: 'blur' 
      }
    ];
    
    // 设置验证规则 - 数值化得分
    newRules[`scoreInfo.${item.itemId}.score`] = [
      { 
        required: true, 
        message: `请输入${item.name}的数值化得分`, 
        trigger: 'blur' 
      },
      { 
        type: 'number', 
        min: 0, 
        max: 100, 
        message: `${item.name}的有效数值化得分范围为0-100分`, 
        trigger: 'blur' 
      }
    ];
  });
  
  // 更新验证规则
  Object.assign(rules, newRules);
};

// 重置表单
const resetForm = () => {
  formData.scoreInfo = {};
  formData.remark = '';
  testItems.value = [];
  
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 关闭对话框
const handleClose = () => {
  // 如果有未保存的数据，询问用户是否确认关闭
  const hasData = Object.values(formData.scoreInfo).some(item => 
    (item.grade !== null && item.grade !== undefined) || 
    (item.score !== null && item.score !== undefined)
  );
  
  if (hasData || formData.remark) {
    ElMessageBox.confirm('有未保存的数据，确认关闭吗？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      dialogVisible.value = false;
    }).catch(() => {
      // 用户取消关闭
    });
  } else {
    dialogVisible.value = false;
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      
      try {
        // 构造提交数据，符合后端DTO格式
        let scoreInfo = [];
        
        if (props.isModify) {
          // 修改模式，使用SingleItemScoreInfoDTO格式
          scoreInfo = Object.entries(formData.scoreInfo).map(([itemId, itemData]) => ({
            id: testItems.value.find(item => item.itemId == itemId)?.id, // 从测试项中找到对应的id
            itemId: parseInt(itemId),
            grade: itemData.grade,   // 原始成绩
            score: itemData.score    // 数值化得分
          }));
          
          const submitData = {
            studentId: props.studentInfo.studentId,
            scoreInfoDTOS: scoreInfo
          };
          
          console.log('修改数据:', submitData);
          
          // 调用修改API
          const res = await updateStudentTestDataApi(props.studentInfo.studentId, submitData);
          
          if (res && res.code === 1) {
            ElMessage.success('体测数据修改成功');
            dialogVisible.value = false;
            emit('refresh'); // 通知父组件刷新数据
          } else {
            ElMessage.error(res?.msg || '体测数据修改失败');
          }
        } else {
          // 录入模式，使用原来的SubmitScoreInfoDTO格式
          scoreInfo = Object.entries(formData.scoreInfo).map(([itemId, itemData]) => ({
            itemId: parseInt(itemId),
            grade: itemData.grade,   // 原始成绩
            score: itemData.score    // 数值化得分
          }));
          
          const submitData = {
            studentId: props.studentInfo.studentId,
            scoreInfo: scoreInfo
          };
          
          console.log('提交数据:', submitData);
          
          // 调用提交API
          const res = await submitStudentTestDataApi(props.studentInfo.studentId, submitData);
          
          if (res && res.code === 1) {
            ElMessage.success('体测数据提交成功');
            dialogVisible.value = false;
            emit('refresh'); // 通知父组件刷新数据
          } else {
            ElMessage.error(res?.msg || '体测数据提交失败');
          }
        }
      } catch (error) {
        console.error('提交数据失败', error);
        ElMessage.error('提交数据失败：' + (error.message || '未知错误'));
      } finally {
        submitting.value = false;
      }
    } else {
      ElMessage.warning('请正确填写所有必填项');
    }
  });
};

// 获取年级文本
const getGradeText = (gradeVal) => {
  if (gradeVal === null || gradeVal === undefined) return '未知';
  
  // 数字转中文
  const numToChinese = (num) => {
    const chineseNums = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'];
    return chineseNums[num] || num;
  };
  
  // 小学 1-6年级
  if (gradeVal >= 1 && gradeVal <= 6) {
    return `小学${numToChinese(gradeVal)}年级`;
  }
  // 初中 7-9年级
  else if (gradeVal >= 7 && gradeVal <= 9) {
    return `初中${numToChinese(gradeVal - 6)}年级`;
  }
  // 高中 10-12年级
  else if (gradeVal >= 10 && gradeVal <= 12) {
    return `高中${numToChinese(gradeVal - 9)}年级`;
  }
  // 大学 13-16年级
  else if (gradeVal >= 13 && gradeVal <= 16) {
    return `大学${numToChinese(gradeVal - 12)}年级`;
  }
  
  return `${gradeVal}年级`;
};
</script>

<style scoped>
.loading-container {
  min-height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.empty-data {
  min-height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.student-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.info-item {
  display: flex;
  align-items: center;
}

.label {
  color: #606266;
  font-weight: bold;
  margin-right: 5px;
}

.value {
  color: #303133;
}

.test-item-form-item {
  margin-bottom: 25px;
  padding-bottom: 10px;
  border-bottom: 1px dashed #ebeef5;
}

.score-input-container {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.score-input-header {
  display: flex;
  margin-bottom: 8px;
}

.input-label {
  flex: 1;
  font-size: 13px;
  color: #909399;
  padding: 0 8px;
}

.score-input-row {
  display: flex;
  gap: 20px;
  width: 100%;
}

.nested-form-item {
  flex: 1;
  margin-bottom: 0;
}

.nested-form-item :deep(.el-form-item__content) {
  display: flex;
  align-items: center;
}

.unit-text {
  color: #909399;
  margin-left: 5px;
  min-width: 20px;
}

.tags-container {
  display: flex;
  gap: 8px;
  margin-top: 8px;
}

.item-tag {
  margin-right: 5px;
}

.hint-text {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* 确保在表单验证不通过时显示错误信息 */
:deep(.el-form-item.is-error .el-input-number) {
  border-color: #f56c6c;
}

:deep(.el-form-item__error) {
  position: absolute;
  top: 100%;
  left: 0;
}
</style> 